The Difference Between jest.spyOn and jest.mock

When I first started to write unit tests for react applications, I found that it is confusing whether I should use jest.spyOn or jest.mock.
The golden rule is that:
  1. jest.mock is used to mock a JavaScript module.
2. jest.spyOn is used to mock what we imported from that module. But it requires an object to spy on.
Let’s look at this super simple example:
utils.js is a module. We can use jest.mock to mock this module then getName and getAddress are automatically mocked.
getName and getAddress are what we imported from utils.js module. We can use jest.spyOn to return specified values if either getName or getAddress is called. But jest requires us to first provide an object in order to use spyOn.
The way how we import has a significant effect on how we mock a particular function in different scenarios.
For the first one:
we cannot really use spyOn as there is no object we can spy on. We cannot spy on a module like:
This is illegal. In order to spy on getName or getAddress, it is required to import everything as an object and spy on that object like this:
But how do I mock the return values of getName and getAddress if I do not want to import everything as an object?
The answer is to use jest.mock.
Firstly, we mock the entire module like this:
Now everything from this module is automatically mocked.
Secondly, in each test scenario, we mock the return value like this:
One last thing we need to keep in mind is that:
the order of mockReturnValue and render a component is important.
The first ‘getName test’ is correct. The second ‘getAddress test’ is incorrect.
If we render a component first but mockReturnValue later, then it is impossible to get the desired values. It is because, at the time when the component is rendered, the function already runs.
💡Also learn about the crucial role testing plays in ensuring quality and reliability before product release:
👉 To read more such articles, sign up for free on Differ.
Conclusion 1. Use jest.mock to mock a module, 2. use jest.spyOn to mock functions from an object ( import * as Something from …), 3. mock first and render late.
  1. 1. Use jest.mock to mock a module,
  1. 2. use jest.spyOn to mock functions from an object ( import * as Something from …),
  1. 3. mock first and render late.

© ming 2021 - 2025